#The obo file should end with a newline

import re

from go_node import *

class obo_parser:
	"""Parses obo files"""
	def __init__(self, filename):
		self.filename = filename
		self.file = open(filename, "r")
		self.tree = {}
		
	def parse(self):
		"""
		Returns a dictionary of go_node objects, indexed by the GO ids
		"""
		self.tree = {} #inorder to reparse
		#file = open("obo_sample.txt", "r")
		if not self.remove_header():
			return None
		node = go_node()
	
		while(True):
			line = self.file.readline()
			if not line:
				break
			line = line[:-1]
			if not line:
				self.tree[node['id']] = node
				node = None
				continue
			if line.lower() == "[term]":
				node = go_node()
				node.isa = []
				continue
			elif line[:1] == "[":
				if not self.remove_header():
					break
				node = go_node()
				continue
			(key, value) = line.split(':', 1)
			value = value.strip()
			if key == 'id':
				node['id'] = int(value[3:])
			elif key == 'name':
				node['name'] = value
			elif key == 'namespace':
				node['namespace'] = value
			elif key == 'def':
				node['definition'] = value.split('"')[1]
			elif key == 'is_a':
				node.isa.append(int(value.split('!')[0].strip()[3:]))
		self.file.close()
		return self.tree

	def remove_header(self):
		"""
		Skips all the lines till [term] is found
		"""
		while(True):
			line = self.file.readline()
			if not line:
				return None
			line = line[:-1]
			if line.lower() == "[term]":
				return True
